<?php
  header('Content-type: application/json');
  date_default_timezone_set('UTC');

  $params = array();
  foreach (array('loadSaveUrl','targetNs','clientKey','location','searchType','sid') as $p) {
    $params[$p] = sprintf("%s",$_REQUEST[$p]);
  }

  $s = str_replace('xmlns="dsOILMAP"','',file_get_contents(
     $params['loadSaveUrl']
    ,false
    ,stream_context_create(
      array('http' => array(
         'method'  => 'POST'
        ,'header'  => 'Content-type: text/xml'
        ,'content' => makePOST($params,$params['targetNs'])
      ))
    )
  ));

  $scenarioTags = array(
     'location' => array('GetScenariosByLocationResponse','GetScenariosByLocationResult')
    ,'sid'      => array('GetScenarioResponse'           ,'GetScenarioResult')
  );

  $ns = array(
    'soap' => 'http://schemas.xmlsoap.org/soap/envelope/'
  );
  $xml = simplexml_load_string($s);
  $xml = simplexml_load_string($xml->children($ns['soap'])->{'Body'}->children()->{$scenarioTags[$params['searchType']][0]}[0]->children()->{$scenarioTags[$params['searchType']][1]});
  $scenarios = array();
  foreach (($params['searchType'] == 'location' ? $xml->{'Scenario'} : array($xml)) as $scenario) {
    $env = array();
    foreach ($scenario->{'Environments'} as $envs) {
      foreach ($envs as $e) {
        array_push($env,array(
           'id'         => sprintf("%s",$e->{'ID'})
          ,'sourceName' => sprintf("%s",$e->{'SourceName'})
          ,'type'       => sprintf("%s",$e->{'Type'})
          ,'scenarioId' => sprintf("%s",$e->{'ScenarioID'})
          ,'speed'      => sprintf("%s",$e->{'Speed'})
          ,'direction'  => sprintf("%s",$e->{'Direction'})
          ,'envType'    => sprintf("%s",$e->{'EnvType'})
        ));
      }
    }
    $oil = array();
    foreach ($scenario->{'OilInfo'} as $o) {
      array_push($oil,array(
           'id'              => sprintf("%s",$o->{'ID'})
          ,'oilType'         => sprintf("%s",$o->{'OilType'})
          ,'amount'          => sprintf("%s",$o->{'Amount'})
          ,'releaseDuration' => sprintf("%s",$o->{'ReleaseDuration'})
          ,'amountUnits'     => sprintf("%s",$o->{'AmountUnits'})
      ));
    }
    // ignore TZ in the incoming StartDate
    preg_match("/^(\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d)(.*)/",sprintf("%s",$scenario->{'StartDate'}),$startDate);
    array_push($scenarios,array(
       'id'        => sprintf("%s",$scenario->{'ID'})
      ,'caseName'  => sprintf("%s",$scenario->{'CaseName'})
      ,'startDate' => date("Y-m-d H:i",strtotime($startDate[1].' UTC'))
      ,'duration'  => sprintf("%s",$scenario->{'Duration'})
      ,'lon'       => sprintf("%s",$scenario->{'Lon'})
      ,'lat'       => sprintf("%s",$scenario->{'Lat'})
      ,'oilinfoId' => sprintf("%s",$scenario->{'OilInfo_ID'})
      ,'waterTemp' => sprintf("%s",$scenario->{'WaterTemp'})
      ,'path'      => sprintf("%s",$scenario->{'Path'})
      ,'location'  => sprintf("%s",$scenario->{'Location'})
      ,'userKey'   => sprintf("%s",$scenario->{'UserKey'})
      ,'env'       => count($env) > 0 ? $env : null
      ,'oil'       => count($oil) > 0 ? $oil : null
    ));
  }

  $caseName = array();
  foreach ($scenarios as $k => $v) {
    $caseName[$k] = $v['caseName'];
  }
  array_multisort($caseName,SORT_ASC,$scenarios);

  echo(json_encode(array('data' => $scenarios)));

  function makePOST($params,$targetNs) {
    if ($params['searchType'] == 'location') {
      return <<< EOPOST
        <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
          <SOAP-ENV:Body>
            <tns:GetScenariosByLocation xmlns:tns="$targetNs">
              <tns:ClientKey>$params[clientKey]</tns:ClientKey>
              <tns:Location>$params[location]</tns:Location>
            </tns:GetScenariosByLocation>
          </SOAP-ENV:Body>
        </SOAP-ENV:Envelope>
EOPOST;
    }
    else if ($params['searchType'] == 'sid') {
      return <<< EOPOST
        <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
          <SOAP-ENV:Body>
            <tns:GetScenario xmlns:tns="$targetNs">
              <tns:ClientKey>$params[clientKey]</tns:ClientKey>
              <tns:Sid>$params[sid]</tns:Sid>
            </tns:GetScenario>
          </SOAP-ENV:Body>
        </SOAP-ENV:Envelope>
EOPOST;
    }
  }
?>
